<template>
  <div class="add-order">
    <!-- 订单详情 -->
    <el-drawer
      :title="formData.id?'编辑':'添加'"
      :visible.sync="$store.state.order.showAddDiglog"
      direction="rtl"
      size="70%"
      @close="btnCancle"
      @open="openDrawer"
    >
      <div class="detail-base">
        <el-form ref="formData" :model="formData" :rules="roles" label-width="100px">
          <div class="detail-base-1" style="padding-top:20px">
            <el-form-item label="店铺名称：" prop="shop_name">
              <el-select v-model="formData.shop_name" :disabled="isSelect" placeholder="请选择" size="small" clearable @change="changeOrder($event)" @clear="resetOrder">
                <el-option
                  v-for="(shop_name,id) in $store.state.order.shopnamelist"
                  :key="id"
                  :label="shop_name"
                  :value="shop_name"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="选择用户：" prop="user_name">
              <el-select v-model="formData.user_name" :disabled="isSelect" placeholder="请选择" size="small" clearable @change="changeUser($event)" @clear="resetUser">
                <el-option
                  v-for="(user_name,id) in $store.state.order.userlist"
                  :key="id"
                  :value="user_name"
                />
              </el-select>
            </el-form-item>
          </div>
          <div style="padding-bottom:20px" class="detail-base-1">
            <el-form-item label="配送方式：" prop="delivery_meth">
              <el-select v-model="formData.delivery_meth" :disabled="isSelect" placeholder="请选择" size="small">
                <el-option
                  v-for="(delivery_meth,id) in distributlist"
                  :key="id"
                  :label="delivery_meth"
                  :value="delivery_meth"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="状态：" prop="sts">
              <el-select v-model="formData.sts" placeholder="请选择" size="small">
                <el-option
                  v-for="(sts,id) in statelist"
                  :key="id"
                  :label="sts"
                  :value="sts"
                />
              </el-select>
            </el-form-item>
          </div>
          <div style="padding-bottom:20px" class="detail-base-1">
            <el-form-item label="配送地址：" style="width:1000px" prop="delivery_addr">
              <el-input v-model="formData.delivery_addr" type="textarea" style="flex:6" :disabled="isSelect" />
            </el-form-item>
          </div>
          <div style="padding-bottom:20px" class="detail-base-1">
            <el-form-item label="联系方式：" prop="ctct_tel">
              <el-input v-model="formData.ctct_tel" size="small" style="width:50%" placeholder="请选择" :disabled="isSelect" />
            </el-form-item>
            <el-form-item label="收货人：" prop="ctct_name">
              <el-input v-model="formData.ctct_name" size="small" style="width:50%" placeholder="请选择" :disabled="isSelect" />
            </el-form-item>
          </div>
          <div style="padding-bottom:20px" class="detail-base-1">
            <el-form-item label="活动优惠：">
              <el-select v-model="formData.activity" placeholder="请选择" size="small" :disabled="isSelect">
                <el-option
                  v-for="(activity,id) in activitylist"
                  :key="id"
                  :label="activity"
                  :value="activity"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="包装：">
              <el-select v-model="formData.pkg" placeholder="请选择" size="small" :disabled="isSelect">
                <el-option
                  v-for="(pkg,id) in pkglist"
                  :key="id"
                  :label="pkg"
                  :value="pkg"
                />
              </el-select>
            </el-form-item>
          </div>
          <div style="padding-bottom:20px" class="detail-base-1">
            <el-form-item label="优惠券：">
              <el-select v-model="formData.coupon" placeholder="请选择" size="small" :disabled="isSelect">
                <el-option
                  v-for="(coupon,id) in $store.state.order.couponlist"
                  :key="id"
                  :label="coupon"
                  :value="coupon"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="配送费：" prop="delivery_fee">
              <el-select v-model="formData.delivery_fee" placeholder="请选择" size="small" :disabled="isSelect">
                <el-option
                  v-for="(delivery_fee,id) in delivery_feelist"
                  :key="id"
                  :label="delivery_fee"
                  :value="delivery_fee"
                />
              </el-select>
            </el-form-item>
          </div>
          <div class="detail-base">
            <h3>选择商品</h3>
            <el-table
              ref="multipleTable"
              :data="$store.state.order.goodDataList"
              tooltip-effect="dark"
              style="width: 100%"
              height="300"
              @select="handleSelectChange($event)"
              @select-all="handelSelect($event)"
            >
              <el-table-column
                v-if="!isSelect"
                type="selection"
                width="55"
              />
              <el-table-column
                prop="id"
                label="商品编号"
                width="120"
              />
              <el-table-column
                prop="good_name"
                label="商品名"
                width="120"
              />
              <el-table-column
                prop="shop_name"
                label="所属店铺"
                show-overflow-tooltip
              />
              <el-table-column
                prop="shop_img"
                label="商品图"
                show-overflow-tooltip
              />
              <el-table-column
                prop="original_prc"
                label="销售价"
                show-overflow-tooltip
              />
              <el-table-column
                prop="activity"
                label="参与活动"
                show-overflow-tooltip
              />
            </el-table>
            <div class="page">
              <span>统计 ￥{{ formData.ordr_amt= `${total}` }}</span>
              <el-pagination
                background
                :current-page="page.page"
                :page-sizes="[1, 3, 5, 7]"
                :page-size="page.size"
                layout="total, prev, pager, next, sizes, jumper"
                :total="page.total"
                @size-change="editSizeChange"
                @current-change="editCurrentChange"
              />
            </div>
          </div>
          <div class="detail-base">
            <div style="padding:60px 0 20px 0">
              <span>合计：</span>
              <span style="color:red;">￥{{ formData.ordr_amt= `${total}` }}</span>
            </div>
          </div>
          <div class="detail-base" style="height:100px">
            <div slot="footer" class="dialog-footer">
              <el-button @click="btnCancle">取 消</el-button>
              <el-button type="primary" @click="handleOrder">确 定</el-button>
            </div>
          </div>
        </el-form>
      </div>
    </el-drawer>
  </div>
</template>
<script>
import { getGoodList, getShopListOfUser, getUserListOfShop, getUserShopData, getGoodListOfName, addOrder, editOrder, getGoodListOfPage } from '@/api/order.js'

export default {
  name: 'AddOrder',
  props: {
    adddrawer: {
      type: Boolean

    }
  },
  data() {
    return {
      isSelect: false,
      tableData: [],
      shopnameId: '',
      formData: {
        shop_name: '', // 店铺名称
        user_name: '', // 用户
        sts: '',
        delivery_meth: '',
        ctct_tel: '', // 联系方式
        activity: '', // 活动
        pkg: '', // 包装
        coupon: '', // 优惠券
        delivery_addr: '', // 配送地址
        delivery_fee: '',
        ordr_amt: 0,
        user_id: '',
        shop_id: '',
        shoplist: [],
        ctct_name: '',
        ordr_time: ''
      },
      pkglist: ['不包装', '包装'],
      couponslist: [], // 优惠券列表
      distributlist: [], // 配送方式列表
      statelist: ['待支付', '待配送', '待发货', '售后退款', '已经取消', '已经完成'], // 状态列表
      activitylist: ['秒杀活动', '打折促销'], // 活动优惠券列表
      delivery_feelist: ['￥: 1', '￥: 2', '￥: 3'],
      roles: {
        shop_name: [{ required: true, message: '店铺名不能为空', trigger: 'blur' }],
        user_name: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
        delivery_meth: [{ required: true, message: '配送方式不能为空', trigger: 'blur' }],
        ctct_tel: [{ required: true, message: '联系方式不能为空', trigger: 'blur' },
          { patter: /^1[3|5|7|8|9]\d{9}$/, message: '联系方式不能为空', trigger: 'blur' }],
        sts: [{ required: true, message: '状态不能为空', trigger: 'blur' }],
        delivery_addr: [{ required: true, message: '配送地址不能为空', trigger: 'blur' }],
        ctct_name: [{ required: true, message: '收货人不能为空', trigger: 'blur' }]
      },
      page: {
        page: 1,
        size: 3,
        total: 0
      },
      totalPrice: 0
      // selectList: []
      // totalPriceOfMeth: 0,
      // totalPriceOfCoupon: 0
    }
  },
  computed: {
    total() {
      if (this.formData.coupon && this.formData.delivery_fee) {
        return this.totalPrice - parseFloat(this.formData.coupon) + parseFloat(this.formData.delivery_fee.substring(2))
      }
      if (this.formData.coupon) {
        return this.totalPrice - parseFloat(this.formData.coupon)
      }
      if (this.formData.coupon) {
        return this.totalPrice + parseFloat(this.formData.delivery_fee.substring(2))
      }
      return this.totalPrice
    }
  },
  created() {
    var timer = setInterval(() => {
      if (this.$store.state.order.orderId) {
        this.$store.state.order.handleOrderData.forEach(value => {
          if (value.id === this.$store.state.order.orderId) {
            this.formData = value
            this.isSelect = true
            clearInterval(timer)
          }
        })
      }
    }, 200)
  },
  methods: {
    // 重置店铺名称列表
    resetOrder() {
      if (!this.formData.user_name) {
        this.$store.dispatch('order/getShopData')
      }
    },
    // 重置用户列表
    resetUser() {
      if (!this.formData.shop_name) {
        return this.$store.dispatch('order/getUserData')
      }
      getGoodListOfName({ shop_name: this.formData.shop_name }).then((res) => {
        console.log(res)
        this.page.total = res.total
        this.$store.state.order.goodDataList = res.data
      })
    },
    // 全选按钮
    handelSelect(e) {
      this.formData.ordr_amt = 0
      this.formData.shoplist = []
      // var arr = []
      e.forEach(value => {
        // if (arr.indexOf(value.id) === -1) {
        //   arr.push(value.id)
        //   this.selectList.push(value)
        // }
        this.formData.ordr_amt += parseFloat(value.original_prc)
        this.totalPrice = this.formData.ordr_amt
        this.formData.shoplist.push(value)
      })
      this.$store.state.order.goodDataList.forEach(value => {
        this.formData.shop_id = value.shop_id
      })
      if (this.formData.coupon) {
        this.formData.ordr_amt = parseFloat(this.formData.ordr_amt) - parseFloat(this.formData.coupon.trim())
      }
      if (this.formData.ordr_amt < 0) {
        return (this.formData.ordr_amt = 0)
      }
    },
    // 选中某项商品
    handleSelectChange(e) {
      console.log(this.totalPrice)
      this.formData.ordr_amt = 0
      this.formData.shoplist = []
      e.forEach(value => {
        // this.selectList.forEach(v1 => {
        //   if (v1.id === value.id) {
        //     arr1.push(value)
        //   }
        // })

        this.formData.ordr_amt += parseFloat(value.original_prc)
        this.totalPrice = this.formData.ordr_amt
        this.formData.shoplist.push(value)
      })
      // this.selectList = arr1
      // console.log(this.selectList)
      this.$store.state.order.goodDataList.forEach(value => {
        this.formData.shop_id = value.shop_id
      })
      if (this.formData.coupon) {
        this.formData.ordr_amt = parseFloat(this.formData.ordr_amt) - parseFloat(this.formData.coupon.trim())
      }
      if (this.formData.ordr_amt < 0) {
        return (this.formData.ordr_amt = 0)
      }
    },
    // 选择用户
    changeUser(e) {
      // 获取用户列表
      const userlist = this.$store.state.order.fullUserList.filter(v1 => {
        return v1.username === e
      })
      this.formData.user_id = userlist[0].id
      // 根据用户名获取店铺列表
      getShopListOfUser(userlist[0].id).then((res) => {
        var newArr1 = []
        if (res.data.length > 0) {
          res.data.forEach(value => {
            if (newArr1.indexOf(value.shop_name) === -1) {
              newArr1.push(value.shop_name)
            }
          })
        }
        this.$store.state.order.shopnamelist = newArr1
        getGoodListOfName({ user_id: this.formData.user_id, shop_name: this.formData.shop_name }).then((res) => {
          this.page.total = res.total
          this.$store.state.order.goodDataList = res.data
          return Promise.resolve()
        }).catch((err) => {
          this.$message.error(err.message)
        })
      })
      // 如果店铺被选中
      if (this.formData.shop_name) {
        var newArr = []
        getUserShopData({ shop_name: this.formData.shop_name, userid: this.formData.user_id }).then((res) => {
          if (res.data.length > 0 && res.data[0].to_shop) {
            newArr.push('到店自取')
          }
          if (res.data.length > 0 && res.data[0].city_delivery.stand_by) {
            newArr.push('同城配送')
          }
          if (res.data.length > 0 && res.data[0].rgnl_delivery.stand_by) {
            newArr.push('跨区配送')
          }
          this.distributlist = newArr
          // this.$store.state.order.goodDataList = res.data
        })
      }
    },
    // 选择店铺
    changeOrder(e) {
      // 根据店铺名获取用户列表
      getUserListOfShop(e).then((res) => {
        var newArr = []
        if (res.data.length > 0) {
          res.data.forEach(value => {
            if (newArr.indexOf(value.username) === -1) {
              newArr.push(value.username)
            }
          })
        }
        this.$store.state.order.userlist = newArr
        getGoodListOfName({ userid: this.formData.user_id, shop_name: e }).then((res) => {
          console.log(res)
          this.page.total = res.total
          this.$store.state.order.goodDataList = res.data
          return Promise.resolve()
        }).catch((err) => {
          this.$message.error(err.message)
        })
      })
      if (this.formData.user_name) {
        const newArr = []
        getUserShopData({ shop_name: this.formData.shop_name, userid: this.formData.user_id }).then((res) => {
          if (res.data.length > 0 && res.data[0].to_shop) {
            newArr.push('到店自取')
          }
          if (res.data.length > 0 && res.data[0].city_delivery.stand_by) {
            newArr.push('同城配送')
          }
          if (res.data.length > 0 && res.data[0].rgnl_delivery.stand_by) {
            newArr.push('跨区配送')
          }
          this.distributlist = newArr
        })
      }
    },
    // 抽屉打开时
    openDrawer() {
      this.$store.dispatch('order/getOrderData')
      this.$store.dispatch('order/getShopData')
      this.$store.dispatch('order/getCouponData')
      this.$store.dispatch('order/getUserData')
      if (this.$store.state.order.orderId) {
        getGoodList(this.$store.state.order.shopId).then((res) => {
          this.$store.state.order.goodDataList = res.data
        }).then(() => {
          this.getGoodData()
        })
        return
      }
      this.$store.dispatch('order/getShopDataList').then((res) => {
        this.page.total = res
        this.getGoodData()
      })
    },
    // 根据页码和条数获取商品列表
    getGoodData() {
      getGoodListOfPage({ ...this.page, shop_name: this.formData.shop_name, user_id: this.formData.user_id }).then((res) => {
        this.$store.state.order.goodDataList = res.data
      })
    },
    handleSelectionChange() {

    },
    editSizeChange(size) {
      this.page.size = size
      this.getGoodData()
    },
    editCurrentChange(current) {
      // for (var i = 0; i <= this.selectList.length; i++) {
      //   this.$refs.multipleTable.toggleRowSelection(this.selectList[i], true)
      // }
      this.page.page = current
      this.getGoodData()
    },
    handleOrder() {
      var date = new Date()
      var Y = date.getFullYear()
      var M = date.getMonth() + 1
      M = M < 10 ? ('0' + M) : M
      var D = date.getDate()
      D = D < 10 ? ('0' + D) : D
      var h = date.getHours()
      h = h < 10 ? ('0' + h) : h
      var m = date.getMinutes()
      m = m < 10 ? ('0' + m) : m
      var s = date.getSeconds()
      s = s < 10 ? ('0' + s) : s
      var ordr_time = ` ${Y + '-'}${M + '-'}${D} ${h + ':'}${m + ':'}${s}`
      this.formData.ordr_time = ordr_time
      this.$refs.formData.validate().then(() => {
        if (this.isSelect) {
          // 修改订单
          editOrder({ ...this.formData, id: this.$store.state.order.orderId }).then((res) => {
            this.$store.dispatch('order/getOrderData')
            this.$message.success('修改订单成功')
            this.btnCancle()
          }).catch((err) => {
            this.$message.error(err.message)
          }).catch(() => {
            this.$message.error('取消订单修改')
          })
        } else {
          // 添加订单
          addOrder(this.formData).then(() => {
            this.$store.dispatch('order/getOrderData')
            this.$message.success('添加订单成功')
            this.btnCancle()
          }).catch((err) => {
            this.$message.error(err.message)
          })
        }
      }).catch(() => {
        this.$message.error('验证不通过')
      })
    },
    btnCancle() {
      setTimeout(() => {
        this.formData = {
          shop_name: '', // 店铺名称
          user_name: '', // 用户
          state: '',
          delivery_meth: '',
          ctct_tel: '', // 联系方式
          activity: '', // 活动
          pkg: '', // 包装
          coupon: '', // 优惠券
          delivery_addr: '', // 配送地址
          delivery_fee: '',
          ordr_amt: 0,
          user_id: '',
          shop_id: ''
        }
        this.$store.state.order.userlist = []
        this.$store.state.order.shopnamelist = []
      }, 200)
      this.$store.state.order.showAddDiglog = false
      this.$store.state.order.orderId = ''
      this.isSelect = false
    }
  }
}
</script>
<style lang="scss" scoped>
::v-deep .el-drawer__header {
    margin-top: 10px;
    margin-bottom: 10px;
}
.detail-base {
  border-top: 1px solid #e3e3e7;
  padding-left: 20px;
  padding-right: 20px;
  .detail-base-1 {
    display: flex;
    justify-content: space-between;
    align-items: center;
    .el-form-item {
      margin: 0;
    }
    .detail-base-2 {
        display: flex;
        align-items: center;
        span {
            flex: 1;
        }
        .el-input {
            flex: 2;
        }
    }
  }
  .detail-base-2 {
    display: flex;
  }
}
::v-deep .el-drawer__body {
  overflow: auto;
}
.page {
    display: flex;
    margin: 20px 0;
    justify-content: space-between;
    align-items: center;
}
.dialog-footer {
    display: flex;
    height: 100%;
    align-items: center;
    justify-content: center;
}
</style>
